package com.cch.security;

import com.cch.service.UserDetailService;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.ArrayList;

/**
 * @author cch
 * @date 2025年05月21日 15:23
 */
public class PhoneNumAuthenticationProvider implements AuthenticationProvider {

    public UserDetailService userDetailService;


    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        PhoneNumAuthenticationToken authenticationToken = (PhoneNumAuthenticationToken) authentication;

        String mobile = (String) authenticationToken.getPrincipal();

        UserDetails userDetails = userDetailService.loadUserByPhoneNum(mobile);
        if (userDetails == null){
            throw new InternalAuthenticationServiceException("无法获取用户信息");
        }

        // 此时鉴权成功后，应当重新 new 一个拥有鉴权的 authenticationResult 返回
        PhoneNumAuthenticationToken authenticationResult = new PhoneNumAuthenticationToken(userDetails, new ArrayList<>());

        authenticationResult.setDetails(authenticationToken.getDetails());

        return authenticationResult;
    }

    @Override
    public boolean supports(Class<?> authentication) {
        // 判断 authentication 是不是 SmsCodeAuthenticationToken 的子类或子接口
        return PhoneNumAuthenticationToken.class.isAssignableFrom(authentication);
    }

    public UserDetailService getUserDetailService() {
        return userDetailService;
    }

    public void setUserDetailService(UserDetailService userDetailService) {
        this.userDetailService = userDetailService;
    }

}
